import { Suspense, lazy, useEffect, useState } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { Provider } from "react-redux";
import "./App.scss";
import store from "./store";
import { AutoUpdate } from "./components/AutoUpdate";
// import { ipcRenderer } from "electron";

const Login = lazy(() => import("./pages/login"));
const Home = lazy(() => import("./pages/home"));

const App = (): JSX.Element => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [progress, setProgress] = useState(0);
  const handleDownload = () => {
    window.ipcRenderer.invoke("update-download", {});
  };
  const handleCancel = () => {
    // window.api.download();
    setIsModalOpen(false);
  };

  useEffect(() => {
    window.ipcRenderer.on("update-error", (event, data) => {
      console.log("updateError", event, data);
    });
    window.ipcRenderer.on("update-available", (event, data) => {
      console.log("updateAvailable", event, data);
      setIsModalOpen(true);
    });
    window.ipcRenderer.on("download-progress", (event, data) => {
      console.log("downloadProgress", event, data);
      const { percent } = data;
      const per = parseInt(percent);
      setProgress(per);
    });
  });
  return (
    <div className="app">
      <Suspense fallback={<div>lodding....</div>}>
        <Provider store={store}>
          <Routes>
            <Route path="/" element={<Navigate to="/login" />}></Route>
            <Route path="/login" Component={Login}></Route>
            <Route path="/home" Component={Home}></Route>
          </Routes>
        </Provider>
      </Suspense>
      <AutoUpdate
        isModalOpen={isModalOpen}
        percent={progress}
        onDownload={handleDownload}
        onCancel={handleCancel}
      ></AutoUpdate>
    </div>
  );
};

export default App;
